package com.example.educationcommunity.controller;

import com.example.educationcommunity.dto.GiteeUser;
import com.example.educationcommunity.mapper.UserMapper;
import com.example.educationcommunity.model.User;
import com.example.educationcommunity.model.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

@Controller
public class RegisterController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/register")
    private String register(){
        return "register";
    }
    @PostMapping("/register")
    private String doRegister(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              HttpServletResponse response,
                              Model model){
        model.addAttribute(username);
        model.addAttribute(password);
        if(username==null || username=="")
        {
            model.addAttribute("error","用户名不能为空");
            return "register";
        }
        if(password==null || password == "")
        {
            model.addAttribute("error","密码不能为空");
            return "register";
        }
        UserExample example = new UserExample();
        example.createCriteria()
                .andAccountIdEqualTo(username);
        List<User> users = userMapper.selectByExample(example);
        if(users.size() != 0)
        {
            model.addAttribute("error","用户名已经被注册了");
            return "register";
        }
        User user =new User();
        user.setAccountId(username);
        user.setPassword(password);
        user.setGmtCreate(System.currentTimeMillis());
        user.setGmtModified(user.getGmtCreate());
        user.setName("小明");
        user.setIsAdmin(false);
        user.setQuestionCount(0);
        user.setCommentCount(0);
        user.setActive(0);
        user.setAvatarUrl("https://pic.imgdb.cn/item/60a9dd9135c5199ba7deab59.jpg");
        String token = UUID.randomUUID().toString();
        user.setToken(token);
        userMapper.insert(user);
        response.addCookie(new Cookie("token",token));
        return "redirect:/";
    }
}
